package com.example.learnspringboot.service;

import com.example.learnspringboot.entity.User;
import com.example.learnspringboot.exception.ServiceException;
import com.example.learnspringboot.mapper.UserMapper;
import com.example.learnspringboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能:业务逻辑处理
 * 作者:每天都要敲代码
 * 日期:2023/10/17 17:10
 */
@Service
//通过@Service将UserService注入到spring容器中去
public class UserService {

    @Autowired
    UserMapper userMapper;

    public void insertUser(User user){
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void deleteUser(Integer id) {
        userMapper.delete(id);
    }

    public void batchDeleteUser(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.delete(id);  // 7  - 8
        }
    }

//    查数据肯定是有返回值的,所以用list类型
    public List<User> searchAllUser() {
        return userMapper.searchAll();
    }

    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }


    // 验证用户账户是否合法
    public User login(User user) {
        // 根据用户名查询数据库的用户信息
        User dbUser = userMapper.selectByUserName(user.getUsername());
        if (dbUser == null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        //生成token
        String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public User register(User user) {
        User dbuser = userMapper.selectByUserName(user.getUsername());
        if(dbuser != null){
            //抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
        return user;
    }
}
